{% extends 'base_generic.html' %}
{% load i18n %}

{% block content %}
<div class="container-fluid py-4">
    <h1 class="mb-4">{% translate "AI Chat" %}</h1>

    <div class="card shadow-sm mb-4">
        <div class="card-body d-flex flex-column" style="height: 60vh; overflow-y: auto;">
            <div id="chat-messages" class="flex-grow-1">
                {% for message in chat_history %}
                    {% if message.role == 'user' %}
                        <div class="alert alert-primary user-message">
                            <strong>{% translate "You" %}:</strong> {{ message.content }}
                        </div>
                    {% else %}
                        <div class="alert alert-secondary ai-message">
                            <strong>{% translate "AI" %}:</strong> {{ message.content }}
                        </div>
                    {% endif %}
                {% empty %}
                    <p class="text-muted text-center">{% translate "Start chatting with the AI!" %}</p>
                {% endfor %}
            </div>
        </div>
        <div class="card-footer d-flex align-items-center bg-light">
            <input type="text" id="user-input" class="form-control me-2" placeholder="{% translate 'Type your message here...' %}">
            <button id="send-button" class="btn btn-primary">{% translate "Send" %}</button>
            <button id="clear-button" class="btn btn-outline-secondary ms-2">{% translate "Clear Chat" %}</button>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const chatMessages = document.getElementById('chat-messages');
        const userInput = document.getElementById('user-input');
        const sendButton = document.getElementById('send-button');
        const clearButton = document.getElementById('clear-button');

        // Scroll to the bottom of the chat window
        function scrollToBottom() {
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // Send message function
        async function sendMessage() {
            const message = userInput.value.trim();
            if (message === '') return;

            // Add user message to UI
            chatMessages.innerHTML += `
                <div class="alert alert-primary user-message">
                    <strong>{% translate "You" %}:</strong> ${message}
                </div>
            `;
            userInput.value = '';
            scrollToBottom();

            try {
                const response = await fetch('{% url "catalog:ai_chat" %}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken'),
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: JSON.stringify({ message: message })
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || 'Failed to get AI response');
                }

                const data = await response.json();
                chatMessages.innerHTML += `
                    <div class="alert alert-secondary ai-message">
                        <strong>{% translate "AI" %}:</strong> ${data.response}
                    </div>
                `;
            } catch (error) {
                console.error('Error sending message:', error);
                chatMessages.innerHTML += `
                    <div class="alert alert-danger ai-message">
                        <strong>{% translate "Error" %}:</strong> ${error.message || 'An unexpected error occurred.'}
                    </div>
                `;
            }
            scrollToBottom();
        }

        // Clear chat history function
        async function clearChatHistory() {
            if (!confirm('{% translate "Are you sure you want to clear the chat history?" %}')) {
                return;
            }

            try {
                const response = await fetch('{% url "catalog:clear_chat_history" %}', {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': getCookie('csrftoken'),
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || 'Failed to clear chat history');
                }

                const data = await response.json();
                alert(data.message);
                chatMessages.innerHTML = '<p class="text-muted text-center">{% translate "Start chatting with the AI!" %}</p>';
            } catch (error) {
                console.error('Error clearing chat history:', error);
                alert('Error clearing chat history: ' + (error.message || 'An unexpected error occurred.'));
            }
        }

        // Event listeners
        sendButton.addEventListener('click', sendMessage);
        userInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
        clearButton.addEventListener('click', clearChatHistory);

        // Helper function to get CSRF token
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        // Initial scroll to bottom
        scrollToBottom();
    });
</script>

<style>
    .user-message {
        background-color: #e0f7fa; /* Light blue for user messages */
        border-color: #b2ebf2;
        margin-left: auto;
        margin-right: 0;
        text-align: right;
    }
    .ai-message {
        background-color: #f1f8e9; /* Light green for AI messages */
        border-color: #c8e6c9;
        margin-left: 0;
        margin-right: auto;
        text-align: left;
    }
    .alert {
        max-width: 75%; /* Limit width of messages */
        word-wrap: break-word;
        white-space: pre-wrap; /* Preserve whitespace and line breaks */
    }
</style>
{% endblock %} 